<template>
  <div class="config-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统配置</span>
          <div>
            <el-button type="primary" size="small" @click="saveConfig">
              保存配置
            </el-button>
            <el-button type="warning" size="small" @click="resetConfig">
              重置
            </el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 网站全局参数配置 -->
        <el-tab-pane label="网站全局参数" name="global">
          <el-form
            :model="globalConfig"
            label-width="120px"
            :rules="globalRules"
            ref="globalFormRef"
          >
            <el-form-item label="系统名称" prop="systemName">
              <el-input
                v-model="globalConfig.systemName"
                placeholder="请输入系统名称"
              ></el-input>
            </el-form-item>

            <el-form-item label="系统Logo">
              <el-upload
                class="logo-uploader"
                action="/api/upload/logo"
                :show-file-list="false"
                :on-success="handleLogoSuccess"
                :before-upload="beforeLogoUpload"
              >
                <img
                  v-if="globalConfig.logo"
                  :src="globalConfig.logo"
                  class="logo"
                />
                <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
              </el-upload>
              <div class="logo-tip">建议上传正方形图片，大小不超过2MB</div>
            </el-form-item>

            <el-form-item label="版权信息" prop="copyright">
              <el-input
                v-model="globalConfig.copyright"
                placeholder="请输入版权信息"
              ></el-input>
            </el-form-item>

            <el-form-item label="默认时间格式" prop="dateFormat">
              <el-select
                v-model="globalConfig.dateFormat"
                placeholder="请选择默认时间格式"
              >
                <el-option label="YYYY-MM-DD" value="YYYY-MM-DD"></el-option>
                <el-option label="YYYY/MM/DD" value="YYYY/MM/DD"></el-option>
                <el-option
                  label="YYYY-MM-DD HH:mm:ss"
                  value="YYYY-MM-DD HH:mm:ss"
                ></el-option>
                <el-option
                  label="YYYY/MM/DD HH:mm:ss"
                  value="YYYY/MM/DD HH:mm:ss"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="是否显示Logo" prop="showLogo">
              <el-switch v-model="globalConfig.showLogo"></el-switch>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 第三方集成配置 -->
        <el-tab-pane label="第三方集成" name="integration">
          <el-form
            :model="integrationConfig"
            label-width="120px"
            :rules="integrationRules"
            ref="integrationFormRef"
          >
            <el-divider content-position="left">API密钥配置</el-divider>
            <el-form-item label="API密钥" prop="apiKey">
              <el-input
                v-model="integrationConfig.apiKey"
                placeholder="请输入API密钥"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item label="API密钥状态" prop="apiKeyEnabled">
              <el-switch v-model="integrationConfig.apiKeyEnabled"></el-switch>
            </el-form-item>

            <el-divider content-position="left">支付配置</el-divider>
            <el-form-item label="支付方式">
              <el-checkbox-group v-model="integrationConfig.paymentMethods">
                <el-checkbox label="alipay">支付宝</el-checkbox>
                <el-checkbox label="wechat">微信支付</el-checkbox>
                <el-checkbox label="unionpay">银联支付</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item
              label="支付宝AppID"
              v-if="integrationConfig.paymentMethods.includes('alipay')"
            >
              <el-input
                v-model="integrationConfig.alipayAppId"
                placeholder="请输入支付宝AppID"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="支付宝密钥"
              v-if="integrationConfig.paymentMethods.includes('alipay')"
            >
              <el-input
                v-model="integrationConfig.alipayKey"
                placeholder="请输入支付宝密钥"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item
              label="微信支付AppID"
              v-if="integrationConfig.paymentMethods.includes('wechat')"
            >
              <el-input
                v-model="integrationConfig.wechatAppId"
                placeholder="请输入微信支付AppID"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="微信支付密钥"
              v-if="integrationConfig.paymentMethods.includes('wechat')"
            >
              <el-input
                v-model="integrationConfig.wechatKey"
                placeholder="请输入微信支付密钥"
                show-password
              ></el-input>
            </el-form-item>

            <el-divider content-position="left">短信/邮件服务配置</el-divider>
            <el-form-item label="短信服务提供商">
              <el-select
                v-model="integrationConfig.smsProvider"
                placeholder="请选择短信服务提供商"
              >
                <el-option label="阿里云" value="aliyun"></el-option>
                <el-option label="腾讯云" value="tencent"></el-option>
                <el-option label="华为云" value="huawei"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="短信AccessKey">
              <el-input
                v-model="integrationConfig.smsAccessKey"
                placeholder="请输入短信AccessKey"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item label="短信SecretKey">
              <el-input
                v-model="integrationConfig.smsSecretKey"
                placeholder="请输入短信SecretKey"
                show-password
              ></el-input>
            </el-form-item>

            <el-form-item label="邮件服务器">
              <el-input
                v-model="integrationConfig.emailServer"
                placeholder="请输入邮件服务器地址"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮件账号">
              <el-input
                v-model="integrationConfig.emailAccount"
                placeholder="请输入邮件账号"
              ></el-input>
            </el-form-item>
            <el-form-item label="邮件密码">
              <el-input
                v-model="integrationConfig.emailPassword"
                placeholder="请输入邮件密码"
                show-password
              ></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 日志设置 -->
        <el-tab-pane label="日志设置" name="log">
          <el-form
            :model="logConfig"
            label-width="120px"
            :rules="logRules"
            ref="logFormRef"
          >
            <el-divider content-position="left">操作日志设置</el-divider>
            <el-form-item label="保存周期(天)" prop="operationLogRetention">
              <el-input-number
                v-model="logConfig.operationLogRetention"
                :min="1"
                :max="365"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="日志级别" prop="operationLogLevel">
              <el-select
                v-model="logConfig.operationLogLevel"
                placeholder="请选择日志级别"
              >
                <el-option label="DEBUG" value="debug"></el-option>
                <el-option label="INFO" value="info"></el-option>
                <el-option label="WARNING" value="warning"></el-option>
                <el-option label="ERROR" value="error"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否记录IP" prop="operationLogRecordIp">
              <el-switch v-model="logConfig.operationLogRecordIp"></el-switch>
            </el-form-item>

            <el-divider content-position="left">审计日志设置</el-divider>
            <el-form-item label="保存周期(天)" prop="auditLogRetention">
              <el-input-number
                v-model="logConfig.auditLogRetention"
                :min="7"
                :max="730"
              ></el-input-number>
            </el-form-item>
            <el-form-item label="日志级别" prop="auditLogLevel">
              <el-select
                v-model="logConfig.auditLogLevel"
                placeholder="请选择日志级别"
              >
                <el-option label="DEBUG" value="debug"></el-option>
                <el-option label="INFO" value="info"></el-option>
                <el-option label="WARNING" value="warning"></el-option>
                <el-option label="ERROR" value="error"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否记录详细信息" prop="auditLogRecordDetail">
              <el-switch v-model="logConfig.auditLogRecordDetail"></el-switch>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import setting from '@/setting'

// 当前激活的选项卡
const activeTab = ref('global')

// 表单引用
const globalFormRef = ref<FormInstance>()
const integrationFormRef = ref<FormInstance>()
const logFormRef = ref<FormInstance>()

// 网站全局参数配置
const globalConfig = reactive({
  systemName: setting.title || 'Movie Hall',
  logo: setting.logo || '/6989d94d0c54ab6b8bcce0fd6f845ed.png',
  copyright: '© 2023 Movie Hall 版权所有',
  dateFormat: 'YYYY-MM-DD HH:mm:ss',
  showLogo: setting.logIsHidde || true,
})

// 第三方集成配置
const integrationConfig = reactive({
  apiKey: '',
  apiKeyEnabled: false,
  paymentMethods: ['alipay', 'wechat'],
  alipayAppId: '',
  alipayKey: '',
  wechatAppId: '',
  wechatKey: '',
  smsProvider: 'aliyun',
  smsAccessKey: '',
  smsSecretKey: '',
  emailServer: 'smtp.example.com',
  emailAccount: 'noreply@example.com',
  emailPassword: '',
})

// 日志设置
const logConfig = reactive({
  operationLogRetention: 30,
  operationLogLevel: 'info',
  operationLogRecordIp: true,
  auditLogRetention: 90,
  auditLogLevel: 'warning',
  auditLogRecordDetail: true,
})

// 表单验证规则
const globalRules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' },
  ],
  copyright: [{ required: true, message: '请输入版权信息', trigger: 'blur' }],
  dateFormat: [
    { required: true, message: '请选择默认时间格式', trigger: 'change' },
  ],
}

const integrationRules = {
  apiKey: [{ required: false, message: '请输入API密钥', trigger: 'blur' }],
}

const logRules = {
  operationLogRetention: [
    { required: true, message: '请输入操作日志保存周期', trigger: 'blur' },
    {
      type: 'number',
      min: 1,
      max: 365,
      message: '保存周期在1到365天之间',
      trigger: 'blur',
    },
  ],
  auditLogRetention: [
    { required: true, message: '请输入审计日志保存周期', trigger: 'blur' },
    {
      type: 'number',
      min: 7,
      max: 730,
      message: '保存周期在7到730天之间',
      trigger: 'blur',
    },
  ],
}

// Logo上传相关方法
const handleLogoSuccess = (res: any) => {
  globalConfig.logo = res.data.url
  ElMessage.success('Logo上传成功')
}

const beforeLogoUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('Logo只能是JPG或PNG格式!')
  }
  if (!isLt2M) {
    ElMessage.error('Logo大小不能超过2MB!')
  }
  return isJPG && isLt2M
}

// 保存配置
const saveConfig = async () => {
  // 验证表单
  try {
    if (activeTab.value === 'global') {
      await globalFormRef.value?.validate()
    } else if (activeTab.value === 'integration') {
      await integrationFormRef.value?.validate()
    } else if (activeTab.value === 'log') {
      await logFormRef.value?.validate()
    }

    // 这里应该调用API保存配置
    // 模拟API调用
    setTimeout(() => {
      ElMessage.success('配置保存成功')
    }, 1000)
  } catch (error) {
    console.error('表单验证失败', error)
    ElMessage.error('表单验证失败，请检查输入')
  }
}

// 重置配置
const resetConfig = () => {
  ElMessageBox.confirm('确定要重置当前配置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      if (activeTab.value === 'global') {
        globalFormRef.value?.resetFields()
      } else if (activeTab.value === 'integration') {
        integrationFormRef.value?.resetFields()
      } else if (activeTab.value === 'log') {
        logFormRef.value?.resetFields()
      }
      ElMessage.success('配置已重置')
    })
    .catch(() => {
      // 取消重置
    })
}

// 初始化加载配置
onMounted(() => {
  // 这里应该调用API获取配置
  // 模拟API调用
  console.log('加载系统配置')
})
</script>

<style scoped lang="scss">
.config-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .logo-uploader {
    width: 120px;
    height: 120px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: border-color 0.3s;

    &:hover {
      border-color: #409eff;
    }

    .logo-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 120px;
      height: 120px;
      line-height: 120px;
      text-align: center;
    }

    .logo {
      width: 120px;
      height: 120px;
      display: block;
    }
  }

  .logo-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
  }

  .el-divider {
    margin: 20px 0;
  }
}
</style>
